/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upc.clase.demo.dao.impl;

import edu.upc.clase.demo.dao.TipoMenuDao;
import edu.upc.clase.demo.entity.TipoMenu;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

/**
 *
 * @author
 */

@Repository
public class TipoMenuDaoImpl extends SimpleJdbcDaoSupport implements TipoMenuDao {
    
    private static Logger log = LoggerFactory.getLogger(TipoMenuDaoImpl.class);

    @Autowired
    public TipoMenuDaoImpl(DataSource dataSource) {
        log.info("Asignando el dataSource");
        setDataSource(dataSource);
    }
    
    @Override
    public Integer insertar(TipoMenu tipoMenu) {
        getJdbcTemplate().update(
                "insert into tipomenu (descripcion) values (?)",
                tipoMenu.getDescripcion());
        return getSimpleJdbcTemplate().queryForInt("select last_insert_id()");
    }

    @Override
    public void actualizar(TipoMenu tipoMenu) {
        getJdbcTemplate().update(
                "update tipomenu set descripcion = ? where id = ?",
                tipoMenu.getDescripcion(), tipoMenu.getId());
    }

    @Override
    public void eliminar(TipoMenu tipoMenu) {
        getJdbcTemplate().update(
                "delete from tipomenu where id = ?", tipoMenu.getId());
    }

    @Override
    public List<TipoMenu> buscarTodos() {
        return getSimpleJdbcTemplate().query(
                "select id, descripcion from tipomenu",
                new BeanPropertyRowMapper<TipoMenu>(TipoMenu.class));
    }
    
    @Override
    public TipoMenu buscar(Integer id) {
        try {
            return getSimpleJdbcTemplate().queryForObject(
                    "select id, descripcion from tipomenu where id = ?",
                    new BeanPropertyRowMapper<TipoMenu>(TipoMenu.class), id);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
}